package server

import (
	"Bulb/data"
	"Bulb/packet"
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

func InitPublic() {
	http.HandleFunc("/ws", handleConnections)
	http.HandleFunc("/", handleIndex)
	//fileServer := http.FileServer(http.Dir("www"))
	//http.Handle("/", fileServer)
}

func handleIndex(w http.ResponseWriter, r *http.Request) {
	uid := authentic(w, r)
	temp := template.Must(template.ParseFiles("www/bulb.html"))
	temp.Execute(w, uid)
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 0, 0)
	if err != nil {
		log.Println("升级失败:", err)
		return
	}
	defer conn.Close()
	//fmt.Println(r.Header.Get("Cookie"))
	cookie, err := r.Cookie("GOSESSIONID")
	if err != nil {
		log.Println("缺少Cookie的升级请求", err)
		return
	}
	uid := GetUidBySessionId(cookie.Value)
	if uid == -1 {
		log.Println("未知错误，UId不存在") //触发条件，服务器重新启动时，处于页面内的用户正在自动重连，即没有http请求直接发送ws连接
		return
	}
	hub.mutex.Lock()
	hub.clients[uid] = conn
	hub.mutex.Unlock()
	data.AddUserBulb(uid)
	fmt.Println("New Conn ", uid)
	SendToAdmin(packet.EncodeServerPacket(packet.NewUserDataInitPacket(data.GetAllUserData())))
	SendToClient(uid, packet.EncodeServerPacket(packet.NewBulbSetPacket(data.BulbStatus[uid])))
	SendToClient(uid, packet.EncodeServerPacket(packet.NewChatMessageInitPacket(data.GetLatestMessages())))
	BroadcastMessage(packet.EncodeServerPacket(packet.NewOnlineCountPacket(data.OnlineCount())))
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("读消息失败:", err)
			hub.unregister <- uid
			break
		}
		pack := packet.ParseClientPacket(string(message))
		handleClientPacket(uid, pack)
	}
}
func handleClientPacket(uid int, pack packet.ClientPacket) {
	switch pack.Action {
	case "send_message":
		if len(pack.Data) > 256 {
			return
		}
		data.AddMessage(uid, pack.Data)
		hub.broadcast <- packet.EncodeServerPacket(
			packet.NewChatMessagePacket(
				data.Message{Sender: uid, Content: pack.Data},
			),
		)
	case "set_button":
		data.SetUserBulb(uid, pack.Data)
		SendToAdmin(packet.EncodeServerPacket(packet.NewUpdateLightBulbPacket(data.UserData{Id: uid, Status: pack.Data})))
		SendToClient(uid, packet.EncodeServerPacket(packet.NewBulbSetPacket(pack.Data)))
	}
}
